<?php
namespace app\controller\toolkit;

use app\exception\ErrnoPlus;
use app\service\AliyunProjectService;
use app\service\AliyunProxyService;
use app\service\AliyunService;
use app\service\DeviceBaseService;
use app\service\ToolkitUserService;
use share\controller\ApiBaseController;
use app\validate\ToolkitUserValidate;


class LoginController extends ToolkitApiController{

    protected $beforeActionList = [
        "checkSign",
    ];

    /**
     * @description: 
     * @return {*}
     * @use: 
     */
    public function initValidate(){
        $this->validate = new ToolkitUserValidate();
    }

    /**
     * 获取注册验证码
     */
    public function login_action(){        
        $input = $this->check();
        $res = ToolkitUserService::checkUser($input['account'],$input['pass']);
        if(empty($res)){
            return self::fail("account or password error",ErrnoPlus::COMMON_INVALID_INPUT);
        }
        $token = $this->authToken($res);
        $res['token'] = $token;
        return self::ok($res);
    }

    /**
     * 发送解绑设备的消息
     */
    public function send_unbind_message_action(){
        $input = $this->check();
        $pk = $input['pk'];
        $dn = $input['dn'];
        $device = DeviceBaseService::getAllByDn($dn,[
            'pk' => $pk
        ]);
        $aliyunParam = [];
        if(empty($device) || empty($device['server_site'])){
            $aliyun = AliyunProxyService::getAliyunService();
            $regionInfo = $aliyun->getRawThingRegoin($pk, $dn);
            if ($regionInfo) {
                $region = AliyunService::getRegionByLocation($regionInfo);
                $aliyunParam['region'] = $region;
            }
            else{
                return self::fail("device not find by default project at aliyun",ErrnoPlus::COMMON_INVALID_INPUT); 
            }
        }
        else{ 
            $aliyunParam['region'] = $device['server_site'];
            $project = AliyunProjectService::getBase($device['aliyun_project_id']);
            if($project){
                $aliyunParam['projectId'] = $project['project_key'];
            }
        }
        $aliyun = AliyunProxyService::getAliyunService($aliyunParam);   
        $propertieDatas = [
            'IsUnbind' => 1
        ];
        $res = $aliyun->setDeviceProperties(null,$pk,$dn,$propertieDatas);
        return self::ok($res);
    }
}
